# -*- coding: utf-8 -*-
from pyquery import PyQuery
from eavic.items import EavicSku
from zc_core.model.items import Catalog, ItemDataSupply
from zc_core.util.common import parse_number
import re
import json
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.model.items import ItemData


# 解析catalog列表
def parse_catalog(response, category1_name, category1_id):
    jpy = PyQuery(response.text)

    div_list = jpy('dt')
    script_text_project = jpy('script')

    cats = list()
    cat1 = _build_catalog(category1_id, category1_name, '', 1)
    cats.append(cat1)
    for index, div in enumerate(div_list.items()):
        # 一级分类
        cat2_name = div.text()
        cat2_id = re.search("\d+", div('a').attr("href")).group()
        cat2 = _build_catalog(cat2_id, cat2_name, category1_id, 2)
        cats.append(cat2)

        cat3_id_list = [re.search('\d+', i).group() for i in
                        re.findall(r'''\+"{}"\)\.append\("<span><a href='(.*?)'>'''.format(cat2_id),
                                   str(script_text_project.text()))]

        cat3_name_list = re.findall(r'''\+"{}"\)\.append\("<span><a href=.*?>"\+"(.*?)"\+'''.format(cat2_id),
                                    script_text_project.text())
        # 二级分类
        for index_1, script in enumerate(cat3_id_list):
            cat3 = _build_catalog(script, cat3_name_list[index_1], cat2_id, 3)
            cats.append(cat3)

    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 解析sku列表页数
def parse_total_page(response):
    jpy = PyQuery(response.text)
    return int(jpy('.ltti-page').remove('span').text().replace('/', ''))


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    category3_id = meta.get('category3_id')
    cat_helper = CatalogHelper()
    jpy = PyQuery(response.text)
    skus = list()
    tr_list = jpy('tbody tr')
    for jpy in tr_list.items():
        skuId = re.search('\d+', jpy('.lts1-thumb').attr('href')).group()
        sku = EavicSku()
        sku['skuId'] = str(skuId)
        sku['batchNo'] = batch_no
        sku['originPrice'] = float(jpy('td:contains("¥")').text().replace('¥','').replace(',',''))
        sku['catalog3Id'] = category3_id
        cat_helper.fill(sku)
        skus.append(sku)
    return skus


# 获取所有一级分类
def parse_catalog_1(response):
    catalog_list_id = list()
    catalog_list_name = list()
    response_text = PyQuery(response.text)
    for i in response_text('.agb_item li').items():
        id = re.search('\d+', i('a').attr('href')).group()
        name = i('.ag-tit').text()
        catalog_list_name.append(name)
        catalog_list_id.append(id)
    return catalog_list_name, catalog_list_id


# 解析详情页
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    cat_helper = CatalogHelper()
    result = EavicSku()
    response_text = PyQuery(response.text)
    sku_name = response_text('.goodsdetail_left h1').text()
    result['skuName'] = sku_name
    # 批次信息
    result['batchNo'] = batch_no
    # 商品ID
    result['skuId'] = sku_id
    # 三级分页
    catalog3Id = str(re.search('\d+',
                               [i for i in response_text('.crumbs a').items()][1]('a').attr('href')).group())

    result['catalog3Id'] = catalog3Id
    cat_helper.fill(result)
    for i in response_text('#package .Ptable tr').items():
        key = i('.tdTitle').text()
        value = i.text().replace(key, '')
        if key.strip() == '型号':
            # 产品型号
            brand_model = value
            if brand_model.strip():
                result['brandModel'] = brand_model.replace('\n', '')
        if key.strip() == '品牌':
            # 产品品牌
            brand_name = value
            if brand_name.strip():
                result['brandName'] = brand_name.replace('\n', '')
    # 主图
    main_picture = [i.attr('bimg') for i in response_text('.items img').items()]
    if main_picture.__len__() != 0:
        result['skuImg'] = main_picture[0]
    # 商品销量总额
    sold_amount = response_text('.cumulativeamount').text()
    result['soldAmount'] = parse_number(sold_amount)
    # 商品属性信息

    # 供应商名称
    supplier_name = response_text('.textm').text()
    result['supplierName'] = supplier_name
    # 商品编号
    goods_code = re.search(r'<div class="gs">(.*?)<', response.text).group(1)
    if goods_code:
        # 供应商商品编码
        result['supplierSkuId'] = goods_code
        if supplier_name == "得力":
            # 供应商商品编号（无后缀）
            plat_code = 'deli'
            result['supplierSkuCode'] = convert_id2code(plat_code, goods_code)
        else:
            result['supplierSkuCode'] = goods_code
    # 供应商衔接
    supplier_link = response_text('.textm').parent('a').attr('href')
    result['supplierSkuLink'] = supplier_link
    return result


# 解析价格
def parse_prices(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    item = ItemDataSupply()
    response_json = json.loads(response.text)
    if response_json.get('success'):
        unit = response_json['unit']
        origin_price = response_json['snatch_price']
        sale_price = response_json['price']
        # 批次信息
        item['batchNo'] = batch_no
        # 商品ID
        item['skuId'] = sku_id
        # 商品初始价格
        item['originPrice'] = parse_number(origin_price)
        # 商品实际价格
        item['salePrice'] = parse_number(sale_price)
        # 商品包装单位
        unit = unit.replace(r'/', '')
        if unit.strip():
            item['unit'] = unit
        return item


# 解析库存
def parse_stock(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    item = ItemDataSupply()
    if response.text.strip().__len__() != 0:
        meta = response.meta
        batch_no = meta.get('batchNo')
        sku_id = meta.get('skuId')
        response_json = json.loads(response.text)
        # 批次信息
        item['batchNo'] = batch_no
        # 商品ID
        item['skuId'] = sku_id
        # 库存数量
        item['stock'] = response_json['stock_num']
        return item
